<template>
  <div class="staff-list">
    <el-card>
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
        <el-input v-model="search" placeholder="搜索姓名/部门/电话/邮箱" style="width:240px;" clearable @keyup.enter="loadData" />
        <div>
          <el-upload v-if="authStore.user?.role === '管理员'" :show-file-list="false" :before-upload="handleImport" accept=".xls,.xlsx">
            <el-button>导入</el-button>
          </el-upload>
          <el-button v-if="authStore.user?.role === '管理员'" @click="handleExport">导出</el-button>
          <el-button v-if="authStore.user?.role === '管理员'" type="primary" @click="goAdd">新增人员</el-button>
        </div>
      </div>
      <el-table :data="list" border stripe style="width:100%;">
        <el-table-column prop="staffId" label="ID" width="80" />
        <el-table-column prop="realName" label="姓名" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="department" label="部门" />
        <el-table-column prop="phone" label="电话" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="roleName" label="角色" />
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="{row}">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录时间" width="160">
          <template #default="{row}">
            {{ formatDateTime(row.lastLoginTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{row}">
            <el-button v-if="authStore.user?.role === '管理员'" size="small" @click="goEdit(row)">编辑</el-button>
            <el-button v-if="authStore.user?.role === '管理员'" size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="limit"
        :total="total"
        :page-sizes="[12,24,36,48]"
        layout="total, prev, pager, next, sizes"
        @current-change="loadData"
        @size-change="loadData"
        style="margin-top:16px;text-align:right;"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getStaffs, deleteStaff, importStaffs, exportStaffs } from '@/api/staff'
import { useAuthStore } from '@/stores/auth'
import { formatDateTime } from '@/utils/dateFormat'

const router = useRouter()
const list = ref([])
const total = ref(0)
const page = ref(1)
const limit = ref(12)
const search = ref('')
const authStore = useAuthStore()

const loadData = async () => {
  const res = await getStaffs({ page: page.value, limit: limit.value, search: search.value })
  list.value = (res.records || []).map(item => ({
    ...item,
    id: item.id || item.staffId
  }))
  total.value = res.total || 0
}
onMounted(loadData)

const goAdd = () => router.push('/staff/add')
const goEdit = row => router.push(`/staff/edit/${row.id}`)
const handleDelete = row => {
  const id = Number(row.id)
  if (!id || isNaN(id)) {
    ElMessage.error('无效的ID，无法删除')
    return
  }
  ElMessageBox.confirm('确定要删除该人员吗？','提示',{type:'warning'}).then(async()=>{
    try {
      await deleteStaff(id)
      ElMessage.success('删除成功')
      loadData()
    } catch (error) {
      if (error?.response?.data?.message?.includes('存在关联数据')) {
        ElMessage.error('删除失败：该人员有关联工单，无法直接删除！')
      } else {
        ElMessage.error('删除失败，请稍后重试')
      }
    }
  })
}
const handleImport = async (file) => {
  await importStaffs(file)
  ElMessage.success('导入成功')
  loadData()
  return false
}
const handleExport = async () => {
  const res = await exportStaffs()
  const url = window.URL.createObjectURL(new Blob([res]))
  const link = document.createElement('a')
  link.href = url
  link.download = '人员数据.xlsx'
  link.click()
  window.URL.revokeObjectURL(url)
}
</script>

<style scoped>
.staff-list {
  padding: 32px 0;
}
</style> 